package com.yuanye.gwcit.fragments;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.hardware.usb.UsbDevice;
import android.hardware.usb.UsbManager;
import android.os.Build;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.annotation.RequiresApi;

import com.yuanye.gwcit.R;
import com.yuanye.yeecho.base.BaseFragment;
import com.yuanye.yeecho.utils.YY;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;

@RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
public class UsbFragment extends BaseFragment {
    
    String TAG = UsbFragment.class.getSimpleName();

    IntentFilter filter;
    UsbReceiver mUsbReceiver;
    List<String> usbNames = new ArrayList<>(Arrays.asList("侧一3.0","侧一2.0","侧二3.0","侧二2.0","下","中","上","TYPE-C"));
    List<String> busNames = new ArrayList<>(Arrays.asList("8-1","7-1","6-1","5-1","2-1.1","2-1.2","2-1.3","2-1.4."));
    List<MyUsbBean> usbBeans = new ArrayList<>();
    View mainView;
    UsbManager usbManager;

    public UsbFragment() {
        setTaskName("USB检测");
        filter = new IntentFilter();
        filter.addAction(UsbManager.ACTION_USB_DEVICE_ATTACHED);
        filter.addAction(UsbManager.ACTION_USB_DEVICE_DETACHED);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mainView = inflater.inflate(R.layout.frag_usb, container, false);
        usbBeans.clear();
        usbBeans.add(new MyUsbBean("8-1", (TextView) mainView.findViewById(R.id.tvCe13)));
        usbBeans.add(new MyUsbBean("7-1", (TextView) mainView.findViewById(R.id.tvCe12)));
        usbBeans.add(new MyUsbBean("6-1", (TextView) mainView.findViewById(R.id.tvCe23)));
        usbBeans.add(new MyUsbBean("5-1", (TextView) mainView.findViewById(R.id.tvCe22)));
        usbBeans.add(new MyUsbBean("2-1.1", (TextView) mainView.findViewById(R.id.tvDown)));
        usbBeans.add(new MyUsbBean("2-1.2", (TextView) mainView.findViewById(R.id.tvMid)));
        usbBeans.add(new MyUsbBean("2-1.3", (TextView) mainView.findViewById(R.id.tvUp)));
//        usbBeans.add(new MyUsbBean("2-1.4.", (TextView) mainView.findViewById(R.id.tvTypeC)));

        usbManager = (UsbManager) requireContext().getSystemService(Context.USB_SERVICE);
        return mainView;
    }


    @Override
    public void execTask() {

        handler.post(new Runnable() {
            @Override
            public void run() {
                for (MyUsbBean bean: usbBeans){
                    bean.setRecognized(false);
                    bean.TextView.setBackgroundColor(getResources().getColor(R.color.text_disable));
                }
            }
        });

        HashMap<String, UsbDevice> deviceList = usbManager.getDeviceList();
        for (UsbDevice device: deviceList.values()){
            if (isUsbDisk(device)){
                String serialNumber = device.getSerialNumber();
                String busName = getBusName(serialNumber);
                if (busName != null){
                    lightUp(busName);
                }
            }
        }
        if (mUsbReceiver == null){
            mUsbReceiver = new UsbReceiver();
            requireContext().registerReceiver(mUsbReceiver, filter);
        }
    }

    @Override
    public void stopTask() {
        if (mUsbReceiver != null){
            requireContext().unregisterReceiver(mUsbReceiver);
        }
    }

    private void lightUp(final String busName){
        handler.post(new Runnable() {
            @Override
            public void run() {
                if (busName != null){
                    MyUsbBean bean = getBeanFromBusName(busName);
                    if (bean != null){
                        bean.setRecognized(true);
                        bean.getTextView().setBackgroundColor(getResources().getColor(R.color.text_enable));
                    }
                    if (isAllRecognized()){
                        passAndNext();
                    }
                }
            }
        });
    }

    private boolean isUsbDisk(UsbDevice device){
        int protocol = device.getInterface(0).getInterfaceProtocol();
        return protocol == 80;
    }

    private boolean isAllRecognized(){
        for (MyUsbBean bean: usbBeans){
            if (!bean.isRecognized()){
                return false;
            }
        }
        return true;
    }

    private MyUsbBean getBeanFromBusName(String busName){
        for (int i=0; i< usbBeans.size();i++){
            MyUsbBean bean = usbBeans.get(i);
            if(bean.getBusName().equals(busName)){
                return bean;
            }
        }
        return null;
    }

    private String getBusName(String serial) {
        String str = YY.execShell("ls /sys/bus/usb/devices");
//        Log.d(TAG, "serial:" + serial);
        for (int i=0; i<busNames.size(); i++){
            String bus = busNames.get(i);
//            Log.d(TAG, "bus:" + bus);
            if(bus.equals("2-1.4.")){
                for(int j=1;j<10;j++){
                    String tempBus = bus+j;
//                    Log.d(TAG, "tempBus:"+tempBus);
                    String sn = YY.execShell("cat /sys/bus/usb/devices/"+ tempBus +"/serial");
//                    Log.d(TAG, "sn=" + sn);
                    if (sn.equals(serial))
                        return tempBus;
                }
            }else {
                if (str.contains(bus)){
//                    Log.d(TAG, "has bus:"+bus);
                    String sn = YY.execShell("cat /sys/bus/usb/devices/"+ bus +"/serial");
//                    Log.d(TAG, "sn=" + sn);
                    if (sn.equals(serial))
                        return bus;
                }else{
//                    Log.d(TAG, "has no bus:"+bus);
                    continue;
                }
            }

        }
        return null;
    }

    class UsbReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (UsbManager.ACTION_USB_DEVICE_ATTACHED.equals(action)) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    // 处理设备连接
                    Log.d(TAG,"检测到USB插入");
                    Log.d(TAG,"getDeviceName:"+device.getDeviceName());
                    Log.d(TAG,"getManufacturerName:"+device.getManufacturerName());
                    Log.d(TAG,"getProductName:"+device.getProductName());
                    Log.d(TAG,"getSerialNumber:"+device.getSerialNumber());
                    Log.d(TAG,"getBusName:"+getBusName(device.getSerialNumber()));
                    if (isUsbDisk(device)){
                        lightUp(getBusName(device.getSerialNumber()));
                    }
                }
            } else if (UsbManager.ACTION_USB_DEVICE_DETACHED.equals(action)) {
                UsbDevice device = intent.getParcelableExtra(UsbManager.EXTRA_DEVICE);
                if (device != null) {
                    // 处理设备断开
                    Log.d(TAG, "onReceive: sn:"+device.getSerialNumber());
                    Log.d(TAG,"检测到USB移除 -- [" + device.getDeviceName() +"]");
                }
            }
        }
    }

    class MyUsbBean{
        String busName;
        TextView TextView;
        boolean recognized;

        public MyUsbBean(String busName, TextView textView) {
            this.busName = busName;
            this.TextView = textView;
        }

        public String getBusName() {
            return busName;
        }

        public void setBusName(String busName) {
            this.busName = busName;
        }

        public android.widget.TextView getTextView() {
            return TextView;
        }

        public void setTextView(android.widget.TextView textView) {
            TextView = textView;
        }

        public boolean isRecognized() {
            return recognized;
        }

        public void setRecognized(boolean recognized) {
            this.recognized = recognized;
        }
    }

}
